package com.mingmen.canting.zhenban;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.ListActivity;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.activity.YiShenHeActivity;
import com.mingmen.canting.adapter.DaishenheListAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.OnItemMenuClickListener;
import com.mingmen.canting.definerecycleview.SwipeMenu;
import com.mingmen.canting.definerecycleview.SwipeMenuBridge;
import com.mingmen.canting.definerecycleview.SwipeMenuCreator;
import com.mingmen.canting.definerecycleview.SwipeMenuItem;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ToastDialog;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.gongyingshang.GongYingShangActivity;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.MyLiveList;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.model.ZhenBanShenHe;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.DividerItemDecoration;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class DaiShenHeListragment extends BaseFragment implements DaishenheListAdapter.OnItemClickListener {

    @BindView(R.id.recyclerview)
    SwipeRecyclerView mRecyclerview;

    @BindView(R.id.check_daishen)
    CheckBox check_daishen;
    LinearLayout llMycollectionBottomDialog;
    Unbinder unbinder;
    @BindView(R.id.btn_digndan)
    Button btn_digndan;
    @BindView(R.id.btn_suofang)
    Button btnSuofang;
    @BindView(R.id.img_list)
    ImageView imgList;

    private String mTitle;

    private static final int MYLIVE_MODE_CHECK = 0;

    private DaishenheListAdapter mRadioAdapter = null;
    private LinearLayoutManager mLinearLayoutManager;


    private int index = 0;
    int myflag = 0;

    public static DaiShenHeListragment getInstance(String title) {
        DaiShenHeListragment sf = new DaiShenHeListragment();
        sf.mTitle = title;
        return sf;
    }


    ToastDialog toastDialog;
    String token;
    List<ZhenBanShenHe.DataBean> dataBeanList = new ArrayList<>();

    @BindView(R.id.frame_layout)
    LinearLayout frame_layout;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.layout_select_all)
    RelativeLayout layout_select_all;
    @BindView(R.id.text_delete)
    TextView text_delete;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_daishenhe, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);

        card_title_tv.setText(mTitle);
        unbinder = ButterKnife.bind(this, v);
        EventBus.getDefault().register(this);
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerview.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration itemDecorationHeader = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
        itemDecorationHeader.setDividerDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider_main_bg_height_1));
        mRecyclerview.addItemDecoration(itemDecorationHeader);
        mRadioAdapter = new DaishenheListAdapter(getActivity(), dataBeanList);
        mRadioAdapter.setOnItemClickListener(this);
        mRecyclerview.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerview.setOnItemMenuClickListener(mMenuItemClickListener);
        mRecyclerview.setAdapter(mRadioAdapter);

        imgList.setVisibility(View.GONE);
        toastDialog = new ToastDialog(getActivity());
        toastDialog.setVerifyClickListener("该条订单正在被审核", new ToastDialog.VerifyClickListener() {
            @Override
            public void cancel() {
            }

            @Override
            public void send(String str) {
            }
        });

        check_daishen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                toastDialog.show();
                if (b) {
                    int flag = 0;
                    myflag = 0;
                    Log.d("applyListapplyList", select.toString());
                    check_daishen.setChecked(true);
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        select.add(dataBeanList.get(i).getApplyId());
                        dataBeanList.get(i).setSelect(true);
                    }
                    text_delete.setVisibility(View.VISIBLE);
                    mRadioAdapter.notifyDataSetChanged();
                    Log.d("AllSelectAllApplist", select.toString());
                    ToolList.removeDuplicateWithOrder(select);
                } else {
                    if (myflag == 1) {

                    } else {
                        select.clear();
                        check_daishen.setChecked(false);
                        text_delete.setVisibility(View.GONE);
                        for (int i = 0; i < dataBeanList.size(); i++) {
                            dataBeanList.get(i).setSelect(false);
                        }
                        mRadioAdapter.notifyDataSetChanged();
                    }
                    ToolList.removeDuplicateWithOrder(select);
                }
            }
        });
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                pageNumber = 1;
                getMyData();

            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;
                    HttpResponse.daiShenhe(token, "0", "", "", "1",pageNumber, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("DaishenHelist", s);

                            BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {

                                ZhenBanShenHe zhenBanShenHe = new ZhenBanShenHe();
                                zhenBanShenHe = GsonUtil.GsonToBean(s, ZhenBanShenHe.class);
                                totalPage=zhenBanShenHe.getTotalPage();
                                Log.d("DataBeanList", dataBeanList.size() + "");
                                dataBeanList.addAll(zhenBanShenHe.getData());
                                if (zhenBanShenHe.getData().size() == 0) {
                                    layout_nodata.setVisibility(View.VISIBLE);
                                    frame_layout.setVisibility(View.GONE);
                                } else {
                                    layout_nodata.setVisibility(View.GONE);
                                    frame_layout.setVisibility(View.VISIBLE);
                                }
                                Log.d("dataBeanListdataBeanList", zhenBanShenHe.getData().size() + "");
                                mRadioAdapter.setDataList(dataBeanList);
                            } else if (baseBean.getCode() == 401) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                                getActivity().finish();
                            } else {
                                Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            layout_nodata.setVisibility(View.VISIBLE);
                            frame_layout.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });

                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });
        return v;
    }

    @Override
    public void initData() {
        getMyData();
    }

    public void getMyData() {

        HttpResponse.daiShenhe(token, "0", "", "", "1",1, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("DaishenHelist", s);

                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    if (dataBeanList.size() > 0) {
                        dataBeanList.clear();
                    }

                    ZhenBanShenHe zhenBanShenHe = new ZhenBanShenHe();
                    zhenBanShenHe = GsonUtil.GsonToBean(s, ZhenBanShenHe.class);
                    totalPage=zhenBanShenHe.getTotalPage();
                    Log.d("DataBeanList", dataBeanList.size() + "");
                    dataBeanList.addAll(zhenBanShenHe.getData());
                    if (zhenBanShenHe.getData().size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                        frame_layout.setVisibility(View.GONE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                        frame_layout.setVisibility(View.VISIBLE);
                    }
                    Log.d("dataBeanListdataBeanList", zhenBanShenHe.getData().size() + "");
                    mRadioAdapter.setDataList(dataBeanList);
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }


            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_nodata.setVisibility(View.VISIBLE);
                frame_layout.setVisibility(View.GONE);
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }


    @OnClick({R.id.recyclerview, R.id.btn_digndan, R.id.btn_suofang, R.id.img_list, R.id.text_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.recyclerview:
                break;


            case R.id.btn_digndan:
                SharePreferenceUtil.put(getActivity(), "modify", "0");
                startActivity(new Intent(getActivity(), ZhenBanDingDanActivity.class));
//                startActivity(new Intent(getActivity(), DingDanActivity.class));
                break;

            case R.id.btn_suofang:
                btn_digndan.setVisibility(View.GONE);
                btnSuofang.setVisibility(View.VISIBLE);
                imgList.setVisibility(View.VISIBLE);
                break;
            case R.id.img_list:
//                startActivity(new Intent(getActivity(), DingDanActivity.class));

                imgList.setVisibility(View.GONE);
                btn_digndan.setVisibility(View.VISIBLE);
                btnSuofang.setVisibility(View.VISIBLE);
                break;
            case R.id.text_delete:
                Log.d("text_deletetext_delete", select.toString());
                String applyIds = MyStringUtils.returnStringBuffer(select);
                deleteIitem(token, applyIds);

                break;
        }
    }

    List<String> select = new ArrayList<>();


    @Override
    public void onItemClickListener(View view, int pos, DaishenheListAdapter.ViewName viewName, List<ZhenBanShenHe.DataBean> myLiveList) {

        switch (view.getId()) {
            case R.id.btn_zhuijia:

                SharePreferenceUtil.put(getActivity(), "applyId", myLiveList.get(pos).getApplyId());
                SharePreferenceUtil.put(getActivity(), "modify", "1");
                HttpResponse.getCookLockStatus(token, "1", new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseBean baseBean = new BaseBean();
                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
//                        startActivity(new Intent(getActivity(), ZhenXiuGaiActivity.class));
                        startActivity(new Intent(getActivity(), ZhenBanDingDanActivity.class));
                        if (baseBean.getCode() == 504) {
                            toastDialog.show();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    toastDialog.dismiss();
                                }
                            }, 2000);
                        } else if (baseBean.getCode() == 0) {
                            startActivity(new Intent(getActivity(), ZhenBanDingDanActivity.class));
//                            startActivity(new Intent(getActivity(), ZhenXiuGaiActivity.class));
                        }
                    }
                });


                break;
            case R.id.view_cb:
            case R.id.layout_check:
            case R.id.check_box:

                for (ZhenBanShenHe.DataBean cart : myLiveList) {
                    if (cart.isSelect()) {   //是否勾上去了
                        Log.d("勾选上了", "勾选上了");
                        myflag = 0;
                        select.add(cart.getApplyId());
                        myflag = 0;
                        Log.d("indexindex", index + "");
                        Log.d("indexindex", myLiveList.size() + "");
                        ToolList.removeDuplicateWithOrder(select);

                        if (select.size() == myLiveList.size()) {
                            check_daishen.setChecked(true);

                        }
                        if (select.size() > 0) {
                            text_delete.setVisibility(View.VISIBLE);
                        } else {
                            text_delete.setVisibility(View.GONE);
                        }
                    } else {
                        Log.d("取消勾选", "取消勾选");
                        myflag = 1;
                        check_daishen.setChecked(false);
                        index--;
                        if (select.size() > 0) {
                            for (int i = 0; i < select.size(); i++) {
                                if (select.get(i).contains(cart.getApplyId())) {
                                    select.remove(i);
                                }
                            }
                        }
                        ToolList.removeDuplicateWithOrder(select);
                        Log.d("applyListapply", select.toString());
                        if (select.size() > 0) {
                            text_delete.setVisibility(View.VISIBLE);
                        } else {
                            text_delete.setVisibility(View.GONE);
                        }
                        if (select.size() > 0) {
                            text_delete.setVisibility(View.VISIBLE);
                        } else {
                            text_delete.setVisibility(View.GONE);
                        }
                        mRadioAdapter.notifyDataSetChanged();
                    }
                }
                break;

            default:
                HttpResponse.getCookLockStatus(token, "4", new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseBean baseBean = new BaseBean();
                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                        if (baseBean.getCode() == 504) {
                            toastDialog.show();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    toastDialog.dismiss();
                                }
                            }, 2000);
                        }
                    }
                });


                break;
        }


    }


    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            int width = getResources().getDimensionPixelSize(R.dimen.qb_px_180);

            int height = ViewGroup.LayoutParams.MATCH_PARENT;


            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()).setBackground(R.drawable.selector_red)
//                    .setImage(R.drawable.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

            }
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = new OnItemMenuClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
//            dataBeanList
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
          /*      Toast.makeText(getActivity(), "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                        .show();*/
                SharePreferenceUtil.put(getActivity(), "applyId", dataBeanList.get(position).getApplyId());
                Log.d("mMenuItemClickListenermMenuItemClickListener", dataBeanList.get(position).getApplyId() + "");
                deleteIitem(token, dataBeanList.get(position).getApplyId());


            } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
                Toast.makeText(getActivity(), "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };

    public void deleteIitem(String token, String applyId) {
        HttpResponse.deleteItem(token, applyId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    getMyData();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 11) {
            getMyData();
        }

    }

}